package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapplication.adapter.NewsAdapter;
import com.example.myapplication.bean.NewsBean;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView newslistView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initEvent();
    }

    public void initView(){
        newslistView = findViewById(R.id.news_listview);

    }
    public void initData(){
        String url ="http://v.juhe.cn/toutiao/index?key=6d27e87ba492e50dd20d47da8af7431c";
//        JSONObject jsonObject =new JSONObject();
//
//        try {
//            jsonObject.put("key","6d27e87ba492e50dd20d47da8af7431c");
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
        RequestQueue requestQueue =Volley.newRequestQueue(MainActivity.this);
    JsonObjectRequest jsonObjectRequest =new JsonObjectRequest(Request.Method.POST, url,  new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {

            Gson gson = new Gson();
            NewsBean newsBean = gson.fromJson(jsonObject.toString(), NewsBean.class);
            List<NewsBean.ResultBean.DataBean> dataBeans = newsBean.getResult().getData();
            newslistView.setAdapter(new NewsAdapter(MainActivity.this,dataBeans));
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            Toast.makeText(MainActivity.this, "网络请求失败", Toast.LENGTH_SHORT).show();
        }
    });
        requestQueue.add(jsonObjectRequest);
    }
    public void initEvent(){

    }
}